"use strict";

var C = require('../common'),
    MongoClient = require('mongodb').MongoClient,
    ObjectID = require('mongodb').ObjectID,
    shortId = require('shorter-mongo-id');

var MongoDbService = function (owner, config) {
    var _cpool = {}; // Active Connection
    var self = this;

    this.connStr = function (name) {
        return config[name].connection;
    };

    this.connect = function(name, callback) {
        if (name in _cpool) {
            callback(null, _cpool[name]);
            return;
        }

        config[name] || C.throwRequired('[' + owner.stack + '].mongodb.[' + name + ']');

        var conn = self.connStr(name);
        conn || C.throwRequired('[' + owner.stack + '].mongodb.[' + name + '].connection');

        MongoClient.connect(conn, function (err, db) {
            if (!err) {
                _cpool[name] = db;
            }

            callback(err, db);
        });
    };
};

MongoDbService.prototype.objectId = function (id) {
    return C._.isString(id) ? new ObjectID(id) : id;
};

MongoDbService.prototype.toShortId = function (id) {
    return shortId(id);
};

module.exports = {

    type: 'service',

    load: function (owner, dbs, cb) {

        var service = new MongoDbService(owner, dbs);
        owner.registerService('mongodb', service);

        cb();
    }
};


